package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.CarBean;
import com.project.mapper.ICarMapper;
import com.project.service.ICarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
public class CarServiceImpl implements ICarService {
    @Autowired
    private ICarMapper carMapper;
    @Override
    public List<CarBean> findByUser(int userId) {
       return carMapper.findByUser(userId);
    }

    @Override
    public void add(int productId, int userId) {
        QueryWrapper<CarBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId",productId);
        qw.eq("fk_userId",userId);
        //按用户的id和商品id查询购物车对象
        CarBean carBean = carMapper.selectOne(qw);
        if (carBean == null){//该用户没有购买该商品，新加购物车对象
            carBean = new CarBean(productId,userId);
            carMapper.insert(carBean);
        }else {
            //该用户购物车中已有该商品，则数量加一;
            carBean.setNum(carBean.getNum() + 1);
            carMapper.updateById(carBean);
        }
    }

    @Override
    public void del(int id) {
        carMapper.deleteById(id);
    }

    @Override
    public void updateNum(int carId, Integer newNum) {
        CarBean carBean = new CarBean();
        carBean.setId(carId);
        carBean.setNum(newNum);
        carMapper.updateById(carBean);
    }
}
